package acs.bridge;

import acs.bridge.model.bm_file_model;
import com.enterprisedt.net.ftp.FTPException;
import com.enterprisedt.net.ftp.FTPFile;
import com.enterprisedt.net.ftp.FileTransferClient;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * acs.bridge
 * User: KuznetsovStV
 * Date: 26.07.13
 * Time: 15:27
 */
public class bm_load_file_ftp implements bm_load_file_interface {
    org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(this.getClass().getName());

    public Logger getLogger() {
        return logger;
    }

    public void setLogger(Logger logger) {
        this.logger = logger;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public String getPort() {
        return port;
    }

    public void setPort(String port) {
        this.port = port;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getSrcPath() {
        return srcPath;
    }

    public void setSrcPath(String srcPath) {
        this.srcPath = srcPath;
    }

    public String getPattern() {
        return pattern;
    }

    public void setPattern(String pattern) {
        this.pattern = pattern;
    }

    private String username;
    private String host;
    private String port;
    private String password;
    private String srcPath;
    private String pattern;
    private List patterns;

    @Override
    public void get_file(String a_file_name, String a_dst_path) throws BridgeException {
        // throw new BridgeException("Test");
        FileTransferClient ftp = null;

        try {
            ftp = new FileTransferClient();

            ftp.setRemoteHost(host);

            ftp.setUserName(username);
            ftp.setPassword(password);
            ftp.setTimeout(60000); // timeout  1 min
            ftp.connect();
            logger.info("FTP session connected");

            ftp.changeDirectory(getSrcPath());
            logger.info("downloading " + a_file_name + " to " + a_dst_path);
            ftp.downloadFile(a_dst_path + a_file_name, a_file_name);
            logger.info("FTP get " + a_file_name);

        } catch (FTPException e) {
            logger.error(e.getMessage() + " (FTPException)");
            logger.error(e.getStackTrace());
            throw new BridgeException(e.getMessage());
        } catch (IOException e) {
            logger.error(e.getMessage() + " (IOException)");
            logger.error(e.getStackTrace());
            throw new BridgeException(e.getMessage());
        }

    }

    @Override
    public List<bm_file_model> get_directory_list() {


        FileTransferClient ftp = null;
        List<bm_file_model> l_dir_list = new ArrayList<bm_file_model>();

        try {
            ftp = new FileTransferClient();
            ftp.setRemoteHost(host);
            ftp.setUserName(username);
            ftp.setPassword(password);
            ftp.setTimeout(60000); // timeout  1 min
            ftp.connect();
            logger.info("FTP session connected");
            ftp.changeDirectory(getSrcPath());

            if (patterns == null)
                patterns = new ArrayList<String>();

            if (pattern != null)
                patterns.add(pattern);

            Iterator ipattern = patterns.iterator();
            while (ipattern.hasNext()) {

                FTPFile[] files = ftp.directoryList((String) ipattern.next());
                SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyy_HHmmssZ");
                sdf.setTimeZone(TimeZone.getTimeZone("GMT-00:00"));
                SimpleDateFormat sd_z_date = new SimpleDateFormat("ddMMyyyy_HHmmss");
                sd_z_date.setTimeZone(TimeZone.getTimeZone("GMT-00:00"));

                for (int i = 0; i < files.length; i++) {
                    String fr_id = files[i].getName() + "_" + sdf.format(files[i].lastModified()) + "_" + files[i].size();
                /*logger.error("fr_id=" + fr_id);*/
                    bm_file_model l_bm_file_model = new bm_file_model();
                    l_bm_file_model.setFr_id(fr_id);
                    l_bm_file_model.setFile_name(files[i].getName());
                    l_bm_file_model.setFile_path(getSrcPath());
                    l_bm_file_model.setLast_modified(sd_z_date.format(files[i].lastModified()));
                    l_bm_file_model.setFile_size(new BigDecimal(files[i].size()));
                    l_dir_list.add(l_bm_file_model);
                }
            }
        } catch (FTPException e) {
            logger.error(e.getMessage());
        } catch (IOException e) {
            logger.error(e.getMessage());
        } catch (ParseException e) {
            logger.error(e.getMessage());
        } finally {
            if (ftp != null)
                try {
                    ftp.disconnect();
                } catch (FTPException e) {
                    logger.error(e.getMessage());
                } catch (IOException e) {
                    logger.error(e.getMessage());
                }
        }

        return l_dir_list;
    }

    public void setPatterns(List patterns) {
        this.patterns = patterns;
    }

    public List getPatterns() {
        return patterns;
    }
}
